package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.PasswordConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.EmployeePageQueryDTO;
import com.sky.entity.Employee;
import com.sky.exception.AccountLockedException;
import com.sky.exception.AccountNotFoundException;
import com.sky.exception.PasswordErrorException;
import com.sky.mapper.EmployeeMapper;
import com.sky.result.PageResult;
import com.sky.service.EmployeeService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;

@Service
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private HttpServletRequest request;//获得请求对象

    @Autowired
    private EmployeeMapper employeeMapper;

    /**
     * 员工登录
     *
     * @param employeeLoginDTO
     * @return
     */
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();

        //1、根据用户名查询数据库中的数据
        Employee employee = employeeMapper.getByUsername(username);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (employee == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        // TODO 实现咯

        password=DigestUtils.md5DigestAsHex(password.getBytes());
        if (!password.equals(employee.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (employee.getStatus() == StatusConstant.DISABLE) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        //3、返回实体对象
        return employee;
    }

    @Override
    public void add(EmployeeDTO employeeDTO) {
        Employee employee = new Employee();
        //属性拷贝
        BeanUtils.copyProperties(employeeDTO, employee);
        //账号状态默认为1，正常状态
        employee.setStatus(StatusConstant.ENABLE);
         //默认密码为123456
         employee.setPassword(DigestUtils.md5DigestAsHex(PasswordConstant.DEFAULT_PASSWORD.getBytes()));
         //创建人、创建时间、修改人、修改时间//aop实现了自动填充了
         /*employee.setCreateTime(LocalDateTime.now());
         employee.setUpdateTime(LocalDateTime.now());

         employee.setCreateUser(BaseContext.getCurrentId());
         employee.setUpdateUser(BaseContext.getCurrentId());*/

//这个是自己写的，是对的
//        Employee employee = new Employee();
//        employee.setId(employeeDTO.getId());
//        employee.setName(employeeDTO.getName());
//        employee.setUsername(employeeDTO.getUsername());
//        employee.setPassword("123456");
//        employee.setPhone(employeeDTO.getPhone());
//        employee.setSex(employeeDTO.getSex());
//        employee.setIdNumber(employeeDTO.getIdNumber());
//        employee.setCreateTime(LocalDateTime.now());
//        employee.setUpdateTime(LocalDateTime.now());
//
//        String jwt = request.getHeader("token");
//        Claims itcast = JwtUtil.parseJWT("itcast", jwt);
//            //错误在这里面md转这个1格式还得这么麻烦
//        Long l = Long.valueOf(itcast.get(JwtClaimsConstant.EMP_ID).toString());
//        employee.setCreateUser(l);
//        employee.setUpdateUser(l);
//        employee.setStatus(StatusConstant.ENABLE);

        employeeMapper.add(employee);
    }

    @Override
    public PageResult selectEmpPage(EmployeePageQueryDTO employeePageQueryDTO) {
        //分页查询插件，先构建页码和记录数，底层用的的LocalTheat
        PageHelper.startPage(employeePageQueryDTO.getPage(),employeePageQueryDTO.getPageSize());

        //返回值要求用这个Page<Employee>接受
        Page<Employee> page= employeeMapper.selectEmpPage(employeePageQueryDTO);
        //返回要新构建一个PageResult，从page，可以得到参数
        return new PageResult(page.getTotal(),page.getResult());
    }

    @Override
    public void startOrStop(Integer status, Long id) {
        //构建成一个对象传过去
        Employee build = Employee.builder().status(status).id(id).build();

        employeeMapper.startOrStop(build);

    }

    @Override
    public Employee selectEmpById(Long id) {

        Employee employee=employeeMapper.selectEmpById(id);

        return employee;
    }

    @Override
    public void updateEmp(EmployeeDTO employeeDTO) {

        Employee employee = new Employee();
        //属性拷贝
        BeanUtils.copyProperties(employeeDTO, employee);

        //aop实现了自动填充了
        /*employee.setUpdateUser(BaseContext.getCurrentId());
        employee.setUpdateTime(LocalDateTime.now());*/

        employeeMapper.updateEmp(employee);

    }

}
